//
//  thread_allocator.cpp
//  JanMalloc
//
//  Created by janhit on 2022/4/16.
//

#include "ThreadAllocator.hpp"
#include "Allocator.hpp"
#include "MemItem.hpp"

namespace MMFAlloc{


ThreadAllocator::ThreadAllocator(const std::thread::id& thdId)
:
mTheadId(thdId)
{
    
}

ThreadAllocator::~ThreadAllocator()
{
    for (auto& v: mAllocators)
        delete v.second;
}

void* ThreadAllocator::Alloc(u32 size)
{
    Allocator* pAllocator = nullptr;
    
    mLock.Lock();
    auto iter = mAllocators.find(size);
    if (iter == mAllocators.end())
    {
        pAllocator = new Allocator(10, size, mTheadId);
        mAllocators.insert({size, pAllocator});
    }
    else
        pAllocator = iter->second;
    
    mLock.Unlock();
    
    return pAllocator->Alloc();
}


void ThreadAllocator::Free(void* addr)
{
    MemoryItem* mi = (MemoryItem*)addr - 1;
    mLock.Lock();
    auto iter = mAllocators.find(mi->Size());
    mLock.Unlock();
    
    if (iter != mAllocators.end())
        iter->second->Free(addr);
}


void ThreadAllocator::Sharink()
{
    for (auto& v: mAllocators)
        v.second->Sharink();
}

}
